package db_manager

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/gorilla/mux"
)

// HTTPServer 是提供设备管理HTTP API的服务器
type HTTPServer struct {
	manager DeviceManager
	server  *http.Server
}

// NewHTTPServer 创建一个新的HTTP API服务器
func NewHTTPServer(manager DeviceManager, addr string) *HTTPServer {
	router := mux.NewRouter()

	server := &HTTPServer{
		manager: manager,
		server: &http.Server{
			Addr:         addr,
			Handler:      router,
			ReadTimeout:  10 * time.Second,
			WriteTimeout: 10 * time.Second,
		},
	}

	// 注册API路由
	router.HandleFunc("/api/devices", server.handleListDevices).Methods("GET")
	router.HandleFunc("/api/devices/{id}", server.handleGetDevice).Methods("GET")
	router.HandleFunc("/api/devices/count", server.handleCountDevices).Methods("GET")
	router.HandleFunc("/api/devices/{id}", server.handleDeleteDevice).Methods("DELETE")

	// 注册Web UI路由
	server.addStaticRoutes(router)

	return server
}

// Start 启动HTTP服务器
func (s *HTTPServer) Start() error {
	log.Printf("设备管理HTTP API服务器启动在 %s", s.server.Addr)
	return s.server.ListenAndServe()
}

// Stop 优雅地停止HTTP服务器
func (s *HTTPServer) Stop(ctx context.Context) error {
	return s.server.Shutdown(ctx)
}

// handleListDevices 处理获取设备列表的请求
func (s *HTTPServer) handleListDevices(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	devices, err := s.manager.ListDevices(ctx)
	if err != nil {
		http.Error(w, fmt.Sprintf("获取设备列表失败: %v", err), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"success": true,
		"data":    devices,
	})
}

// handleGetDevice 处理获取单个设备的请求
func (s *HTTPServer) handleGetDevice(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	vars := mux.Vars(r)
	deviceID := vars["id"]

	device, err := s.manager.GetDevice(ctx, deviceID)
	if err != nil {
		http.Error(w, fmt.Sprintf("获取设备失败: %v", err), http.StatusInternalServerError)
		return
	}

	if device == nil {
		http.Error(w, "设备不存在", http.StatusNotFound)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"success": true,
		"data":    device,
	})
}

// handleCountDevices 处理获取设备数量的请求
func (s *HTTPServer) handleCountDevices(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	count, err := s.manager.CountDevices(ctx)
	if err != nil {
		http.Error(w, fmt.Sprintf("获取设备数量失败: %v", err), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"success": true,
		"count":   count,
	})
}

// handleDeleteDevice 处理删除设备的请求
func (s *HTTPServer) handleDeleteDevice(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	vars := mux.Vars(r)
	deviceID := vars["id"]

	err := s.manager.DeleteDevice(ctx, deviceID)
	if err != nil {
		statusCode := http.StatusInternalServerError
		if err.Error() == fmt.Sprintf("设备不存在: %s", deviceID) {
			statusCode = http.StatusNotFound
		}
		http.Error(w, fmt.Sprintf("删除设备失败: %v", err), statusCode)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]interface{}{
		"success": true,
		"message": fmt.Sprintf("设备 %s 已成功删除", deviceID),
	})
}
